package com.ibuonline.b2b.system.action;

import java.util.List;
import java.util.Set;

import com.dimeng.common.base.BaseAction;
import com.dimeng.common.util.StringUtil;
import com.ibuonline.b2b.common.SysCache;
import com.ibuonline.b2b.common.service.SysPropertyService;
import com.ibuonline.b2b.entity.SysProperty;

public class SysPropertyAction extends BaseAction {
	
	private static final long serialVersionUID = 3282941461897256373L;
	private Set<String> sysPropertyTypes;
	private String type;
	private SysPropertyService propertyService;
	private String[] keys;
	private String[] orders;
	private String[] values;
	
	public String editSysProperty() {
		sysPropertyTypes = SysCache.getSysPropertyTypes();
		return SUCCESS;
	}
	
	public void ajaxGetSysPropertiesByType() {
		//try {
		//	type = new String(type.getBytes("ISO-8859-1"), "GBK");
		//} catch(Exception e) {}
		List<SysProperty> list;
		list = SysCache.getSysPropertiesByType(type);
		StringBuilder sb = new StringBuilder();
		for (SysProperty sp : list) {
			sb.append("{key:\"").append(StringUtil.jsStrEscape(sp.getPropertyKey())).append("\",")
				.append("value:\"").append(StringUtil.jsStrEscape(sp.getPropertyValue()))
				.append("\",displayOrder:").append(sp.getDisplayOrder()).append("},");
		}
		if (sb.length() > 0) sb.deleteCharAt(sb.length()-1); // delete the last comma
		getOut().print("[" + sb + "]");
		getOut().flush();
	}
	
	@SuppressWarnings("unchecked")
	public String saveSysProperty() {
		if (keys != null && keys.length > 0) {
			for (int i = 0; i < keys.length; i++) {
				SysProperty sp = new SysProperty();
				sp.setDisplayOrder(new Integer(orders[i]));
				sp.setPropertyKey(keys[i]);
				sp.setPropertyType(type);
				sp.setPropertyValue(values[i]);
				propertyService.save(sp);
			}
		}
		SysCache.getInstance().refreshSysProperties();
		return editSysProperty();
	}
	
	

	public Set<String> getSysPropertyTypes() {
		return sysPropertyTypes;
	}

	public void setSysPropertyTypes(Set<String> sysPropertyTypes) {
		this.sysPropertyTypes = sysPropertyTypes;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public SysPropertyService getPropertyService() {
		return propertyService;
	}

	public void setPropertyService(SysPropertyService propertyService) {
		this.propertyService = propertyService;
	}

	public String[] getKeys() {
		return keys;
	}

	public void setKeys(String[] keys) {
		this.keys = keys;
	}

	public String[] getOrders() {
		return orders;
	}

	public void setOrders(String[] orders) {
		this.orders = orders;
	}

	public String[] getValues() {
		return values;
	}

	public void setValues(String[] values) {
		this.values = values;
	}
}
